/**
 * Created by jiachenpan on 16/11/18.
 */

export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (('' + time).length === 10) time = parseInt(time) * 1000
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}


export function timestamp2date(timestamp) {
  var time = new Date(timestamp);
  var year = time.getFullYear();
  var month = time.getMonth() + 1;
  var date = time.getDate();
  var hours = time.getHours();
  var minutes = time.getMinutes() < 10 ? '0' + time.getMinutes() : time.getMinutes();
  var seconds = time.getSeconds() < 10 ? '0' + time.getSeconds() : time.getSeconds();
  return year + '-' + month + '-' + date + ' ' + hours + ':' + minutes + ':' + seconds;
}

export function issuedTime(holidays, day, hour) {

  const startDate = new Date();
  let issuedDate = day;
  let issuedMinute = startDate.getMinutes()<10?'0'+startDate.getMinutes():startDate.getMinutes()
  let issuedHour = startDate.getHours()+hour;
  if(issuedHour>23){
    issuedHour = issuedHour-24;
    issuedDate += 1;
  }
  issuedHour = issuedHour<10?'0'+issuedHour:issuedHour;

  for (let i = 0; i < issuedDate; i++) {
    let thisDate = startDate.getTime();
    thisDate += (i+1) * (24 * 3600 * 1000);
    let endDate = new Date(thisDate);
    //拼接日期
    let thisTime = endDate.getFullYear()+'-'+(endDate.getMonth()+1)+'-'+endDate.getDate();
    //是否为周末
    let notWeekday = true;
    if(endDate.getDay()===0||endDate.getDay()===6){
      issuedDate += 1;
      notWeekday = false;
    }
    //是否为休息日
    if(holidays.indexOf(thisTime)!==-1&&notWeekday){
      issuedDate += 1;
    }
  }
  //  开始计算结束日期
  let endDate = startDate.getTime();
  endDate += issuedDate * (24 * 3600 * 1000);
  let issueDate = new Date(endDate);
  let nowDate = issueDate.getFullYear()+'-'+(issueDate.getMonth()+1)+'-'+issueDate.getDate();

  let nowTime = hour!==0?'  '+issuedHour+':'+issuedMinute:' 17:00';
  return nowDate+ nowTime;
}

export function formatTime(time, option) {
  time = +time * 1000
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

//格式化数字 - 每三位加逗号 number:需要转换的数字 n：精确度
export function priceType(number, n) {
  if (n != 0) {
    n = (n > 0 && n <= 20) ? n : 2;
  }
  number = parseFloat((number + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
  var sub_val = number.split(".")[0].split("").reverse();
  var sub_xs = number.split(".")[1];
  var show_html = "";
  for (var i = 0; i < sub_val.length; i++) {
    show_html += sub_val[i] + ((i + 1) % 3 === 0 && (i + 1) !== sub_val.length ? "," : "");
  }
  if (n === 0) {
    return show_html.split("").reverse().join("");
  } else {
    return show_html.split("").reverse().join("") + "." + sub_xs;
  }
}
export const uploadThumbnail = {
  hint: '이미지를 선택하세요',
  loading: '업로드 중……',
  noSupported: '이 기능을 지원할수없는 브라우저입니다  IE10이상 또는 Chrome사용하세요!',
  success: '완료',
  fail: '오류',
  preview: '미리보기',
  btn: {
    off: '취소',
    close: '닫기',
    back: '이전 단계',
    save: '저장'
  },
  error: {
    onlyImg: '지원할 수 없는 타입 입니다',
    outOfSize: '파일 너무 큽니다. 허용 파일 용량 는:',
    lowestPx: '이미지 최소 사이즈 는(폭*높이)：'
  }
}


export const pickerOptions = [{
    text: '今天',
    onClick(picker) {
      const end = new Date()
      const start = new Date(new Date().toDateString())
      end.setTime(start.getTime())
      picker.$emit('pick', [start, end])
    }
  },
  {
    text: '最近一周',
    onClick(picker) {
      const end = new Date(new Date().toDateString())
      const start = new Date()
      start.setTime(end.getTime() - 3600 * 1000 * 24 * 7)
      picker.$emit('pick', [start, end])
    }
  },
  {
    text: '最近一个月',
    onClick(picker) {
      const end = new Date(new Date().toDateString())
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      picker.$emit('pick', [start, end])
    }
  },
  {
    text: '最近三个月',
    onClick(picker) {
      const end = new Date(new Date().toDateString())
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      picker.$emit('pick', [start, end])
    }
  }
]

/**
 * @param {Function} func
 * @param {number} wait
 * @param {boolean} immediate
 * @return {*}
 */
export function debounce(func, wait, immediate) {
  let timeout, args, context, timestamp, result

  const later = function() {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp

    // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last)
    } else {
      timeout = null
      // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args)
        if (!timeout) context = args = null
      }
    }
  }

  return function(...args) {
    context = this
    timestamp = +new Date()
    const callNow = immediate && !timeout
    // 如果延时不存在，重新设定延时
    if (!timeout) timeout = setTimeout(later, wait)
    if (callNow) {
      result = func.apply(context, args)
      context = args = null
    }

    return result
  }
}